package com.yitao.cms.service.banner;

import com.google.common.collect.Lists;
import com.querydsl.core.types.Order;
import com.querydsl.core.types.OrderSpecifier;
import com.skipper.base.bean.DataOutput;
import com.skipper.base.bean.PagedInput;
import com.skipper.base.bean.PagedOutput;
import com.skipper.base.data.querydsl.PredicateBuilder;
import com.skipper.base.service.GenericEntityService;
import com.yitao.client.dto.banner.BannerDto;
import com.yitao.client.model.banner.BannerModel;
import com.yitao.client.model.banner.QBannerModel;
import com.yitao.cms.constant.BaseEnum;
import com.yitao.cms.constant.UserErrorEnum;
import com.yitao.cms.constant.UserSession;
import com.yitao.cms.model.operationUser.OperationUserCmsModel;
import com.yitao.cms.utils.BaseUtils;
import com.yitao.cms.utils.DateUtils;
import com.yitao.cms.vo.banner.BannerInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

/**
 * Banner相关功能
 *
 * @Author:
 * @Date:
 */
@Service
public class BannerCmsService extends GenericEntityService<BannerModel, BannerDto, QBannerModel> {

    @Autowired
    private HttpServletRequest request;

    private BaseUtils baseUtils = BaseUtils.getInstance();

    public BannerCmsService(EntityManager entityManager) {
        super(entityManager);
    }


    /**
     * 新增banner图/广告图
     *
     * @return
     */
    @Transactional
    public DataOutput saveBanner(BannerInfoVo bannerInfoVo, HttpServletRequest request) {
        Date date = new Date();
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) { // 未登录
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getCode());
        }
        BannerModel bannerModel = new BannerModel();
        if (bannerInfoVo.getId() == null) {
            BeanUtils.copyProperties(bannerInfoVo, bannerModel);
            bannerModel.setShopId(userSession.getShopId());
            bannerModel.setSkipUrl(bannerInfoVo.getSkipUrl()); // banner跳转链接
            bannerModel.setBannerUrl(bannerInfoVo.getBannerUrl()); // banner图URL
            bannerModel.setBannerTitle(bannerInfoVo.getBannerTitle());
            bannerModel.setIsDelete(BaseEnum.YesOrNoEnum.NO.getCode());
            bannerModel.setCreateBy(userSession.getId());
            bannerModel.setCreateTime(date);
            bannerModel.setLastUpdateBy(userSession.getId());
            bannerModel.setLastUpdateTime(date);
        } else {
            BannerModel bannerModel1 = queryFactory.select(Q).from(Q).where(Q.id.eq(bannerInfoVo.getId())).fetchOne();
            if (bannerModel1 == null) {
                return baseUtils.getErrorMsg();
            }
            BeanUtils.copyProperties(bannerModel1, bannerModel);
            bannerModel.setLastUpdateBy(userSession.getId());
            bannerModel.setLastUpdateTime(date);
            bannerModel.setBannerTitle(bannerInfoVo.getBannerTitle());
            bannerModel.setBannerUrl(bannerInfoVo.getBannerUrl());
            bannerModel.setSkipUrl(bannerInfoVo.getSkipUrl());
            bannerModel.setSort(bannerInfoVo.getSort());
        }

        repository.save(bannerModel);
        return baseUtils.getSuccessMsg();

    }

    /**
     * 查询banner列表
     */

    public PagedOutput<BannerInfoVo> getBannerListBean(PagedInput pagedInput, BannerInfoVo bannerInfoVo) {
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) { // 未登录
            throw new RuntimeException("未登录");
        }
        bannerInfoVo.setShopId(userSession.getShopId());
        List<BannerInfoVo> bannerInfoVoList = Lists.newArrayList();
        PagedOutput<BannerModel> bannerModelPagedOutput = repository.pagingList(PredicateBuilder.conjunction().
                ifNotNullThenAnd(bannerInfoVo.getShopId(), () -> Q.shopId.in(userSession.getShopId())).
                ifNotNullThenAnd(false, () -> Q.isDelete.eq(BaseEnum.YesOrNoEnum.NO.getCode())).
                get(), pagedInput, new OrderSpecifier<>(Order.DESC, Q.createTime));

        if (bannerModelPagedOutput != null && bannerModelPagedOutput.getData() != null && bannerModelPagedOutput.getData().size() != 0) {
            BannerInfoVo bannerInfoVo1 = null;
            for (BannerModel bannerModel : bannerModelPagedOutput.getData()) {
                bannerInfoVo1 = new BannerInfoVo();
                BeanUtils.copyProperties(bannerModel, bannerInfoVo1);
                if (bannerModel.getCreateTime() != null) {
                    bannerInfoVo1.setCreateTime(DateUtils.getDateSecondFormat(bannerModel.getCreateTime()));
                }
                bannerInfoVoList.add(bannerInfoVo1);
            }
        }
        return new PagedOutput(pagedInput, bannerModelPagedOutput.getTotalElements(), bannerInfoVoList);
    }

    /**
     * 查询banner详情
     */
    public DataOutput<BannerInfoVo> getBannerById(Long bannerId) {
        BannerInfoVo bannerInfoVo = null;
        BannerModel bannerModel = queryFactory.select(Q).from(Q).where(Q.id.eq(bannerId)).fetchOne();
        if (bannerModel != null) {
            bannerInfoVo = new BannerInfoVo();
            BeanUtils.copyProperties(bannerModel, bannerInfoVo);
            if (bannerModel.getCreateTime() != null) {
                bannerInfoVo.setCreateTime(DateUtils.getDateSecondFormat(bannerModel.getCreateTime()));
            }
        }
        return baseUtils.getSuccessMsg(bannerInfoVo);
    }

    /**
     * 删除banner
     */
    @Transactional
    public DataOutput deleteBannerByBannerId(HttpServletRequest request, Long bannerId) {
        Date date = new Date();
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) { // 未登录
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getCode());
        }
        BannerModel bannerModel = queryFactory.select(Q).from(Q).where(Q.id.eq(bannerId)).fetchOne();
        if (bannerModel != null) {
            bannerModel.setIsDelete(BaseEnum.YesOrNoEnum.YES.getCode());
            bannerModel.setLastUpdateTime(date);
            bannerModel.setLastUpdateBy(userSession.getId());
            repository.save(bannerModel);
            return baseUtils.getSuccessMsg();
        }
        return baseUtils.getErrorMsg();
    }


}
